#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json

from bottle import Bottle
from bottle import request, response

from excel.LFREE.LfreeDictUtil import LfreeDictUtil
from excel.LFREE.LfreeObj import LfreeObj

lFreeAdm = Bottle()


@lFreeAdm.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@lFreeAdm.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


# Excel自研数据演算服务
# Vue+ele管理台界面数据接口

class LfreeAdminRoute:
    TEST_SELECT_PAYMENT = 10
    TEST_SELECT_ANB = 7
    TEST_SUM_ASSURED = 1000000
    TEST_GENDER = "M"
    TEST_SMOKER = "N"
    TEST_REPEAT_PLAN = 1
    TEST_REPEAT_GROWTH_RATE = float(1 / 100)
    TEST_CURRENCY = "HKD-U"
    TEST_PROMOTION = "Y"
    TEST_WITHDRAWAL_STARTING_ANB = 66
    TEST_SURRENDER_ANB = 91
    TEST_WITHDRAWAL_YEARS = 0
    TEST_INFLATION = 0
    TEST_FST_YEAR_WITHDRAWAL = 0

    TEST_YEAR = range(101)

    json_data_file = ""
    ERROR_CODE = {
        "80": "数据读取异常错误，请联系管理员",
        "99": "处理参数错误",
        "100": "数据添加失败，请检查服务端日志",
        "102": "数据更新失败，请检查服务端日志",
        "103": "数据删除失败，请检查服务端日志",
        "104": "数据停止失败，请检查服务端日志",
        "105": "数据恢复失败，请检查服务端日志",
        "106": "数据激活失败，请检查服务端日志",
        "109": "数据不存在，数据处理失败",
    }

    impl = None

    def __init__(self, service):
        LfreeAdminRoute.impl = service
        return

    @staticmethod
    @lFreeAdm.post('/initKeyParam')
    def init_cal_param():
        # select_payment = request.forms.
        if request.json is not None:
            select_payment = request.json['select_payment']
            select_anb = request.json['select_anb']
            sum_assured = request.json['sum_assured']
            gender = request.json['gender']
            smoker = request.json['smoker']
            repeat_plan = request.json['repeat_plan']
            repeat_growth_rate = request.json['repeat_growth_rate']
            currency = request.json['currency']
            promotion = request.json['promotion']
            withdrawal_starting_anb = request.json['withdrawal_starting_anb']
            surrender_anb = request.json['surrender_anb']
            withdrawal_years = request.json['withdrawal_years']
            inflation = request.json['inflation']
            fst_year_withdrawal = request.json['fst_year_withdrawal']
            if select_anb == None:
                return {'code': LfreeAdminRoute.ERROR_CODE["99"], 'data': None, 'message': '次年歲'}
            if repeat_growth_rate > 0 and repeat_growth_rate < 1:
                repeat_growth_rate = int(repeat_growth_rate * 100)
            if not promotion is None:
                promotion = 'Y' if promotion else 'N'
            str_res = LfreeDictUtil.make_json_key(select_payment=select_payment, select_anb=select_anb,
                                                  sum_assured=sum_assured, gender=gender, smoker=smoker,
                                                  repeat_plan=repeat_plan, repeat_growth_rate=repeat_growth_rate,
                                                  currency=currency, promotion=promotion,
                                                  withdrawal_starting_anb=withdrawal_starting_anb,
                                                  surrender_anb=surrender_anb, withdrawal_years=withdrawal_years,
                                                  inflation=inflation, fst_year_withdrawal=fst_year_withdrawal)
            str_res = "LFREE-" + str_res
            hitnnt = LfreeAdminRoute.impl.do_chck_key_exist(str_res)
            obj_data = None
            if hitnnt['code'] == 200:
                if hitnnt['data']:
                    obj_data = {"key": str_res, "hit": hitnnt, "res_msg": "中签"}
                else:
                    obj_data = {"key": str_res, "hit": hitnnt, "res_msg": "未中签"}
            else:
                return {'code': 99, 'data': obj_data, 'message': LfreeAdminRoute.ERROR_CODE["99"]}
            return {'code': 200, 'data': obj_data, 'message': ""}

    @staticmethod
    @lFreeAdm.get('/initStdBaseTab')
    def cal_purnm():
        strPram = request.params.strPram
        if strPram is None or len(strPram) == 0:
            return {'code': 99, 'data': None, 'message': LfreeAdminRoute.ERROR_CODE["99"]}
        res = LfreeAdminRoute.impl.do_std_base_tab(str_param=strPram, years=LfreeAdminRoute.TEST_YEAR, withdrawals=[])
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': LfreeAdminRoute.ERROR_CODE["99"]}
        view_list = json.loads(res['data'])
        return {'code': 200, 'data': view_list, 'message': ""}

    @staticmethod
    @lFreeAdm.post('/cal')
    def cal_purnm():
        if request.json is not None:
            strPram = request.json['strPram']
            withdrawals = request.json['withdrawals']
            res = LfreeAdminRoute.impl.do_cal(str_param=strPram, years=LfreeAdminRoute.TEST_YEAR,
                                              withdrawals=withdrawals)
            if res["code"] != 200:
                return {'code': 99, 'data': None, 'message': LfreeAdminRoute.ERROR_CODE["99"]}
            view_list = json.loads(res['data'])
            # view_list = chg_Json2_list(arrays, LfreeObj.DATA_COLUMN)
            return {'code': 200, 'data': view_list, 'message': ""}

    @staticmethod
    @lFreeAdm.get('/initVDBStdIndex')
    def init_vdbstdtab():
        view_list = []
        payment = request.params.tables
        if payment is not None and len(payment) > 0:
            view_list = LfreeAdminRoute.impl.do_get_VDBStdTab_index_opts(str_param=payment)
        return {'code': 200, 'data': view_list['data'], 'message': ""}

    @staticmethod
    @lFreeAdm.get('/loadVDBStdTab')
    def load_vdbstdtab():
        view_list = []
        payment = request.params.tables
        indexs = request.params.indexs
        if payment is not None and len(payment) > 0:
            view_list = LfreeAdminRoute.impl.do_get_VDBStdTab(str_param=payment, int_indexs=int(indexs))
        return {'code': 200, 'data': view_list['data'], 'message': ""}


def get_premium_index(gender, smoker):
    if str(gender).upper() == "M":
        return LfreeObj.GENDER_M_TERM[str(smoker).upper()]
    else:
        return LfreeObj.GENDER_F_TERM[str(smoker).upper()]


def get_mn_premium_index(payment_term):
    return LfreeObj.switch_C8_dict[payment_term]


def chg_json2_list(json_array, data_column):
    rows = []
    data_len = len(json_array[data_column[0]])
    for i in range(data_len):
        data_row = {}
        for j in range(len(data_column)):
            data_row[data_column[j]] = json_array[data_column[j]][i]
        rows.append(data_row)
    return rows
